import _ from 'lodash';
import moment from 'moment';

const availableSearchKeys = ['LIKE', 'IN', 'GE', 'LE', 'GT', 'LT', 'EQ', 'SORT'];

// 获取有效的搜索表单控件
export const getUsefulSearchItems = (list) => {
  if (_.isArray(list)) {
    const usefulFormItems = _.filter(
      list,
      ({ key, Component, searchType }) =>
        _.includes(availableSearchKeys, searchType) && _.isString(key) && Component,
    );
    return _.uniqBy(usefulFormItems, 'key');
  }
  return [];
};

// 格式化查询参数
export const getSearchParams = (values, mappings) => {
  const baseValToStr = (val) => {
    if (_.isString(val) || _.isNumber(val)) {
      return val;
    } else if (_.isArray(val)) {
      return _.filter(val, (item) => _.isString(item) || _.isNumber(item)).join(',');
    } else if (moment.isMoment(val)) {
      return val.valueOf();
    }
  };
  return _.filter(
    _.map(_.keys(values), (key) => {
      switch (key) {
        case 'SORT':
          const targetVal = values[key];
          const formatVal =
            _.isString(targetVal) || _.isNumber(targetVal)
              ? targetVal
              : _.isArray(targetVal) && targetVal.length === 1
              ? _.head(targetVal)
              : '';
          if (_.includes(['ORDERBYASC', 'ORDERBYDESC'], formatVal)) {
            return {
              column: key,
              type: formatVal,
            };
          }
          break;
        default:
          const val = baseValToStr(values[key]);
          if (val) {
            return {
              column: key,
              type: mappings[key],
              values: val,
            };
          }
      }
    }),
    (v) => !!v,
  );
};
